﻿using System;
using System.Web.Mvc;

namespace CID.Web.Support
{
    public class InterfaceCrawlerMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
        {
            try
            {
                return base.GetMetadataForProperty(modelAccessor, containerType, propertyName);
            }
            catch (Exception ex)
            {
                //Try to go up to type tree
                var types = containerType.GetInterfaces();
                foreach (var container in types)
                {
                    if (container.GetProperty(propertyName) != null)
                    {
                        try
                        {
                            return GetMetadataForProperty(modelAccessor, container, propertyName);
                        }
                        catch
                        {
                            //This interface did not work
                        }
                    }
                }
                //If nothing works, then throw the exception
                throw ex;
            }
        }
    }
}